package com.cd.song.controller;

import com.cd.common.controller.BaseController;
import com.cd.common.domain.AjaxResult;
import com.cd.song.api.SongTagRelationService;
import com.cd.song.jpa.domain.SongTagRelation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/song-tag-relations")
public class SongTagRelationController extends BaseController {

    @Autowired
    private SongTagRelationService songTagRelationService;

    @GetMapping
    public AjaxResult getAllRelations() {
        return success(songTagRelationService.findAll());
    }

    @GetMapping("{tagId}")
    public AjaxResult getRelationByTagId(@PathVariable(value = "songId") Long songId,
                                         @PathVariable(value = "tagId") Long tagId) {
        List<SongTagRelation> relations = songTagRelationService.findByTagId(tagId);
            return success(relations);
    }

    @PostMapping
    public AjaxResult createRelation(@RequestBody SongTagRelation relation) {
        return success(songTagRelationService.save(relation));
    }

//    @PutMapping("/{songId}/{tagId}")
//    public ResponseEntity<SongTagRelation> updateRelation(@PathVariable(value = "songId") Long songId,
//                                                          @PathVariable(value = "tagId") String tagId,
//                                                          @RequestBody SongTagRelation relationDetails) {
//        Optional<SongTagRelation> optionalRelation = songTagRelationService.findById(songId, tagId);
//        if (optionalRelation.isPresent()) {
//            SongTagRelation relation = optionalRelation.get();
//            relation.setSongId(relationDetails.getSongId());
//            relation.setTagId(relationDetails.getTagId());
//            final SongTagRelation updatedRelation = songTagRelationService.save(relation);
//            return ResponseEntity.ok(updatedRelation);
//        } else {
//            return ResponseEntity.notFound().build();
//        }
//    }

    @DeleteMapping("/{songId}/{tagId}")
    public AjaxResult deleteRelation(@PathVariable(value = "songId") Long songId,
                                               @PathVariable(value = "tagId") Long tagId) {
        Optional<SongTagRelation> relation = songTagRelationService.findBySongIdAndTagId(songId, tagId);
        if (relation.isPresent()) {
            songTagRelationService.deleteBySongIdAndTagId(songId, tagId);
            return success("删除成功");
        } else {
            return error("删除失败");
        }
    }
}